import type MarkdownIt from "markdown-it"

export interface Options {
  codeCopyButtonTitle: string
  languageLabel?: Record<string, string>
}

export function preWrapperPlugin(md: MarkdownIt, options: Options) {
  const langLabel = Object.fromEntries(
    Object.entries(options.languageLabel || {}).map(([k, v]) => [k.toLowerCase(), v])
  )

  const fence = md.renderer.rules.fence as any

  md.renderer.rules.fence = (...args) => {
    const [tokens, idx] = args
    const token = tokens[idx] as any

    // remove title from info
    token.info = token.info.replace(/\[.*\]/, "")

    const active = / active( |$)/.test(token.info) ? " active" : ""
    token.info = token.info.replace(/ active$/, "").replace(/ active /, " ")

    const lang = extractLang(token.info)
    const label = langLabel[lang.toLowerCase()] || lang.replace(/_/g, " ")
    const CopyIcon = `<div class='icon-copy'></div>`

    return (
      `<div class="language-${lang}${active}">` +
      `<button title="${options.codeCopyButtonTitle}" class="copy copy-code-button">${CopyIcon}</button>` +
      `<span class="lang hljs-language">${label}</span>` +
      fence(...args) +
      "</div>"
    )
  }
}

export function extractTitle(info: string, html = false) {
  if (html) {
    return info.replace(/<!--[^]*?-->/g, "").match(/data-title="(.*?)"/)?.[1] || ""
  }
  return info.match(/\[(.*)\]/)?.[1] || extractLang(info) || "txt"
}

function extractLang(info: string) {
  return info
    .trim()
    .replace(/=(\d*)/, "")
    .replace(/:(no-)?line-numbers({| |$|=\d*).*/, "")
    .replace(/(-vue|{| ).*$/, "")
    .replace(/^vue-html$/, "template")
    .replace(/^ansi$/, "")
}
